#include "stdTcpService.h"
#include <iostream>
using namespace std;
#include <pthread.h>
#include <unistd.h>
#include <json-c/json.h>
/* 线程池 */
#include "threadPool.h"
#include "messageHandler.h"
#include <map>
#include <queue>

std::queue<int> m_queue;
std::map<int,int> m_map;

#define PORT 8080

void *thread_func(void *arg)
{
    // pthread_detach(pthread_self());
    std::shared_ptr<StdTcpSocket> clientSock = *(std::shared_ptr<StdTcpSocket> *)arg;

    string data;

    int readBytes = 0;
    MessageHandler messages(clientSock);
    //messages.setAttrSock(&clientSock);

    while (1)
    {
        data.clear();
        /* 接受客户端信息 */
        readBytes = clientSock->recvMessage(data);
        if (readBytes < 0)
        {
            break;
        }
        else if (readBytes == 0)
        {
            cout << "客户端 "<< clientSock->getAttrConnfd() <<" 下线 " << endl;
            break;
        }
        else
        {
            messages.handleMessage(data);
        }
    }
#if 0
    pthread_exit(NULL);
#else
    return nullptr;
#endif
}

int main()
{
    /* 创建线程池 */
    ThreadPool pool(3,6,10);

    StdTcpServer server;
    /* 设置监听 */
    server.setListen(PORT);

    cout << "等待客户端连接...." << endl;
    int ret = 0;
    while (1)
    {
        std::shared_ptr<StdTcpSocket> clientSock = server.getClientSock();
        /* 程序到这个地方，就意味着有客户端连接*/
        /* 创建线程 */
        pool.addTask(thread_func,&clientSock);


#if 0
        pthread_t tid;
        ret = pthread_create(&tid, NULL, thread_func, &clientSock);
        if (ret == -1)
        {
            perror("thread create error:");
            exit(1);
        }
#endif
        sleep(1);


        

        // sleep(10);
    }



    return 0;
}